package com.ruoyi.project.system.exam.controller;

import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.question.domain.ExamDetail;
import com.ruoyi.project.system.question.domain.ExamRecord;
import com.ruoyi.project.system.question.service.IExamDetailService;
import com.ruoyi.project.system.question.service.IExamRecordService;
import com.ruoyi.project.system.exam.domain.ExamSessionConfig;
import com.ruoyi.project.system.exam.service.IExamSessionConfigService;
import com.ruoyi.project.system.question.domain.Question;
import com.ruoyi.project.system.question.service.IQuestionService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

/**
 * 个人答题考试Controller
 * 
 * @author ruoyi
 */
@Controller
@RequestMapping("/system/exam/personal")
public class PersonalExamController extends BaseController {
    
    private static final Logger logger = LoggerFactory.getLogger(PersonalExamController.class);
    
    private String prefix = "system/exam/personal";
    
    @Autowired
    private IExamSessionConfigService examSessionConfigService;
    
    @Autowired
    private IQuestionService questionService;
    
    @Autowired
    private IExamRecordService examRecordService;
    
    @Autowired
    private IExamDetailService examDetailService;
    
    /**
     * 跳转到选择场次配置页面
     */
    @RequiresPermissions("system:exam:personal:index")
    @GetMapping("/select_config")
    public String selectConfig() {
        return prefix + "/select_config";
    }
    
    /**
     * 跳转到答题页面
     */
    @RequiresPermissions("system:exam:personal:index")
    @GetMapping("/exam")
    public String exam(@RequestParam Long configId, @RequestParam Integer examType, ModelMap mmap) {
        // 获取场次配置信息
        ExamSessionConfig config = examSessionConfigService.selectExamSessionConfigById(configId);
        mmap.put("config", config);
        mmap.put("examType", examType);
        
        // 根据配置获取题目
        Question questionParam = new Question();
        questionParam.setCategoryId(config.getCategoryId());
        if (config.getDifficulty() != null && config.getDifficulty() != 0) {
            questionParam.setDifficulty(config.getDifficulty());
        }
        // 只获取启用状态的题目
        questionParam.setStatus(1);
        
        List<Question> allQuestions = questionService.selectQuestionList(questionParam);
        logger.info("根据配置获取到的题目总数: {}", allQuestions.size());
        logger.info("题目列表: {}", allQuestions);
        
        // 随机抽取指定数量的题目
        List<Question> selectedQuestions = new ArrayList<>();
        if (allQuestions.size() <= config.getQuestionCount()) {
            // 如果总题目数不足或等于要求的数量，直接使用所有题目
            selectedQuestions = new ArrayList<>(allQuestions);
        } else {
            // 如果总题目数超过要求的数量，随机抽取
            Collections.shuffle(allQuestions);
            selectedQuestions = allQuestions.subList(0, config.getQuestionCount());
        }
        
        logger.info("最终选择的题目数量: {}", selectedQuestions.size());
        logger.info("最终选择的题目列表: {}", selectedQuestions);
        
        mmap.put("questions", selectedQuestions);
        return prefix + "/exam";
    }
    
    /**
     * 跳转到个人答题记录详情页面
     */
    @RequiresPermissions("system:exam:personal:index")
    @GetMapping("/detail")
    public String detail(@RequestParam Long recordId, ModelMap mmap) {
        // 获取答题记录
        ExamRecord examRecord = examRecordService.selectExamRecordById(recordId);
        
        // 获取答题详情列表
        ExamDetail detailParam = new ExamDetail();
        detailParam.setRecordId(recordId);
        List<ExamDetail> examDetails = examDetailService.selectExamDetailList(detailParam);
        
        // 为每个答题详情补充题目信息
        for (ExamDetail detail : examDetails) {
            Question question = questionService.selectQuestionById(detail.getQuestionId());
            detail.setQuestion(question);
        }
        
        mmap.put("examRecord", examRecord);
        mmap.put("examDetails", examDetails);
        return prefix + "/detail";
    }
    /**
     * 提交考试结果
     */
    @RequiresPermissions("system:exam:personal:index")
    @RequestMapping("/submit")
    @ResponseBody
    public AjaxResult submitExam(@RequestParam Long configId,
                                 @RequestParam Integer examType,
                                 @RequestParam Integer useTime,
                                 @RequestParam String userAnswers) {
        try {
            // 获取当前用户ID
            Long userId = getUserId();

            // 获取场次配置
            ExamSessionConfig config = examSessionConfigService.selectExamSessionConfigById(configId);

            // 获取题目列表
            Question questionQuery = new Question();
            questionQuery.setCategoryId(config.getCategoryId());
            if (config.getDifficulty() != null && config.getDifficulty() != 0) {
                questionQuery.setDifficulty(config.getDifficulty());
            }
            List<Question> allQuestions = questionService.selectQuestionList(questionQuery);

            // 随机抽取指定数量的题目
            List<Question> selectedQuestions = new ArrayList<>();
            if (allQuestions.size() <= config.getQuestionCount()) {
                selectedQuestions = new ArrayList<>(allQuestions);
            } else {
                Collections.shuffle(allQuestions);
                selectedQuestions = allQuestions.subList(0, config.getQuestionCount());
            }

            // 解析用户答案（格式：题目ID:用户答案,题目ID:用户答案...）
            String[] answerPairs = userAnswers.split(",");
            // 创建一个Map来存储用户答案
            Map<Long, String> answerMap = new HashMap<>();
            for (String pair : answerPairs) {
                if (!pair.isEmpty()) {
                    String[] parts = pair.split(":");
                    if (parts.length == 2) {
                        answerMap.put(Long.valueOf(parts[0]), parts[1]);
                    }
                }
            }

            // 计算成绩
            int correctCount = 0;
            int totalQuestions = selectedQuestions.size();

            // 创建答题详情列表
            List<ExamDetail> examDetails = new ArrayList<>();

            for (Question question : selectedQuestions) {
                String userAnswer = answerMap.get(question.getId());
                boolean isCorrect = false;

                if (userAnswer != null) {
                    // 根据题型判断答案是否正确
                    if (question.getQuestionType() == 4) { // 填空题
                        // 填空题答案比较（忽略大小写和空格）
                        if (userAnswer.trim().toLowerCase().equals(
                                (question.getCorrectAnswer() != null ? question.getCorrectAnswer() : "").trim().toLowerCase())) {
                            correctCount++;
                            isCorrect = true;
                        }
                    } else {
                        // 其他题型答案比较
                        if (userAnswer.equals(question.getCorrectAnswer())) {
                            correctCount++;
                            isCorrect = true;
                        }
                    }
                }

                // 创建答题详情记录
                ExamDetail detail = new ExamDetail();
                detail.setQuestionId(question.getId());
                detail.setUserAnswer(userAnswer);
                detail.setIsCorrect(isCorrect ? 1 : 0);
                examDetails.add(detail);
            }

            int score = Math.round((correctCount * 100.0f / totalQuestions));

            // 保存答题记录
            ExamRecord record = new ExamRecord();
            record.setUserId(userId);
            record.setExamType(examType);
            record.setConfigId(configId);
            record.setScore(score);
            record.setTotalQuestion(totalQuestions);
            record.setCorrectQuestion(correctCount);
            record.setWrongQuestion(totalQuestions - correctCount);
            record.setUseTime(useTime);
            record.setExamDate(new Date());
            examRecordService.insertExamRecord(record);

            // 保存答题详情（关联到答题记录）
            for (ExamDetail detail : examDetails) {
                detail.setRecordId(record.getId());
                examDetailService.insertExamDetail(detail);
            }

            return AjaxResult.success("考试提交成功", record);
        } catch (Exception e) {
            logger.error("提交考试结果时发生错误", e);
            return AjaxResult.error("提交考试结果失败: " + e.getMessage());
        }
    }
}